package com.apchernykh.rozhlasapp.services;

import com.apchernykh.rozhlasapp.player.IPlaybackCallbacks;

import android.os.HandlerThread;
import android.os.Looper;
import android.os.Process;

public abstract class BackgroundPhoneInetNotifiedService extends
		PhoneInetNotifiedService implements IPlaybackCallbacks {
	private Looper mServiceLooper = null;
	protected PlaybackAsyncControlHandler mLocalHandler = null;

	@Override
	public void onDestroy() {
		// ConditionalLog.e("onDestroy disconnected");
		if(mServiceLooper != null)
		{
			mServiceLooper.quit();
		}
		mLocalHandler = null;
		mServiceLooper = null;
		super.onDestroy();
	}

	@Override
	public void onCreate() {
		// Start up the thread running the service. Note that we create a
		// separate thread because the service normally runs in the process's
		// main thread, which we don't want to block. We also make it
		// background priority so CPU-intensive work will not disrupt our UI.
		HandlerThread aBackgroundPlaybackThread = new HandlerThread("AsyncBackgroundPlaybackThread",
				Process.THREAD_PRIORITY_BACKGROUND);
		aBackgroundPlaybackThread.start();
		mServiceLooper = aBackgroundPlaybackThread.getLooper();
		mLocalHandler = new PlaybackAsyncControlHandler(mServiceLooper, this);
		super.onCreate();
	}

	public void reScheduleDelayed(long iDelayMillis, int iWhat, Object iArg) {
		if (mLocalHandler != null) {
			mLocalHandler.sendMessageDelayed(mLocalHandler.obtainMessage(iWhat, iArg), iDelayMillis);
		}
	}

	public void cancelMessage(int iWhat, Object iArg) {
		if (mLocalHandler != null) {
			mLocalHandler.removeMessages(iWhat, iArg);
		}
	}
	
	

	public void reScheduleImmediate(int iWhat, Object iArg) {
		if (mLocalHandler != null) {
			mLocalHandler.removeMessages(iWhat);
			mLocalHandler.sendMessage(mLocalHandler.obtainMessage(iWhat, iArg));
		}
	}

	public void errorDetected() {
		if (mLocalHandler != null) {
			mLocalHandler.removeMessages(PlaybackAsyncControlHandler.START_PLAYBACK);
			mLocalHandler.removeMessages(PlaybackAsyncControlHandler.STOP_PLAYBACK);
			reScheduleImmediate(PlaybackAsyncControlHandler.ERROR_DETECTED, " ");
		}
	}

	public void reScheduleViewsExpiration(long iNextRefresh) {
		if (mLocalHandler != null) {
			mLocalHandler.removeMessages(PlaybackAsyncControlHandler.REFRESH_VIEWS);
			mLocalHandler.sendMessageDelayed(
					mLocalHandler.obtainMessage(PlaybackAsyncControlHandler.REFRESH_VIEWS),
					iNextRefresh - System.currentTimeMillis());
		}
//		ConditionalLog.e(
//				"rescheduled views refresh to "
//						+ String.valueOf(aNextRefresh
//								- System.currentTimeMillis()) + " : "
//						+ String.valueOf(mLocalHandler));
	}

	public void cancelViewsExpiration() {
		if (mLocalHandler != null) {
			mLocalHandler.removeMessages(PlaybackAsyncControlHandler.REFRESH_VIEWS);
		}
//		ConditionalLog.e(
//				"cancelled views refresh " + String.valueOf(mLocalHandler));
	}

}